import EventEmitter from 'eventemitter3';
import winston from 'winston';

/**
 * Default Channel
 * @type {String}
 */
const DEFAULT_CHANNEL = Symbol('DEFAULT_CHANNEL');


/**
 * Used to handle all event flow in server-side
 */
export class Dispatcher extends EventEmitter {
    constructor(channel = DEFAULT_CHANNEL) {
        super();

        this.channel = channel;
    }

    /**
     * Dispatch a action to all listeners
     * @param  {string} options.type    action type
     * @param  {Object} options.payload payload content
     * @return {Dispatcher}             dispatch instance
     */
    dispatch({ type, payload = {} }) {
        winston.debug('dispatched action:', {
            type,
            payload,
            channel: this.channel
        });
        return this.emit(type, payload);
    }
}

/**
 * Default Dispatcher
 * @type {ChannelDispatcher}
 */
const defaultDispatcher = new Dispatcher(DEFAULT_CHANNEL);

export default defaultDispatcher;